package com.defysoft.waukids.main;

import java.util.ArrayList;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Type.WK_SCHOOL;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;

public class Main_JoinMember extends BaseActivity implements OnClickListener{
	EditText et []  = new EditText[4];
	Toolbar toolbar;
	View btn;
	TextView tv,chk_email;
	String email="",pass="",name="",sch="",regId="",rank="",addr="",addposition="";
	RadioGroup radioGroup;
	RadioButton radioButton;
	ArrayList<String> addcode;
	ArrayList<String> addname;
	ArrayList<String> schoolname;
	ArrayList<WK_SCHOOL> schoollist;
	public Sqlite_Connect sqlite_Connect;
	int check =0;
	boolean check_email=false,check_name=false;
	private final int SUCCESS = 10;
	private final int FAIL = 9;
	private final int NETWORK_ERR = 8;
	private final int EMAIL_CHECK = 7;
	private final int SEARCH_ADDR = 6;
	private final int SEARCH_SCHOOL = 5;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.main_joinmember_activity);
		setStartData();
		setStartToolbar();
	}
	
	private void setStartToolbar() {
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	@Override
	public void setStartData() {
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		regId = getIntent().getStringExtra("MEM_UUID");
		toolbar= (Toolbar)findViewById(R.id.MAIN_JOIN_TOOLBAR);
		et[0] = (EditText) findViewById(R.id.MAIN_JOIN_EMAIL);
		et[1] = (EditText) findViewById(R.id.MAIN_JOIN_PASS);
		et[2] = (EditText) findViewById(R.id.MAIN_JOIN_PASSCHECK);
		et[3] = (EditText) findViewById(R.id.MAIN_JOIN_NAME);	
		tv = (TextView)findViewById(R.id.MAIN_JOIN_SCHOOL_SEARCH);
		radioGroup = (RadioGroup)findViewById(R.id.MAIN_JOIN_RANK_RG);		
		chk_email = (TextView) findViewById(R.id.MAIN_JOIN_EMAIL_CHECK);
		btn = (View) findViewById(R.id.MAIN_JOIN_BTN);
		
		tv.setOnClickListener(this);
		chk_email.setOnClickListener(this);
		btn.setOnClickListener(this);
		
		et[0].addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if (check_email == true) {
					chk_email.setVisibility(View.VISIBLE);
					Toast.makeText(Main_JoinMember.this, "중복확인을 다시 해주세요.", Toast.LENGTH_SHORT).show();
					check_email = false;
				}
			}
		});
et[3].addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(et[3].getText().length()>0){
					Pattern ps = Pattern.compile("^[a-zA-Z0-9ㄱ-ㅎ가-흐]+$");//영문, 숫자, 한글만 허용
			        if(!ps.matcher(s).matches()){
			            check_name=false;
			            Toast.makeText(Main_JoinMember.this, "특수문자 사용불가능 합니다.", Toast.LENGTH_LONG).show();
			        	}else{
			        		check_name=true;
			        	}
			        }
				
			}
		});
	}
	
	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho= choice;
		firstThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				switch (cho) {
				case SUCCESS:
					mainThread(SUCCESS);
					break;

				case EMAIL_CHECK:
					mainThread(EMAIL_CHECK);
					break;
					
				case SEARCH_ADDR:
					showAddress();
					break;
					
				case SEARCH_SCHOOL:
					selectSchool();
					break;
				}
				
			}
		});
		firstThread.start();
		startDIal();
	}
	
	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		
		switch (_message.what) {
		case SUCCESS:
			//회원가입 성공
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, (String)_message.obj, Toast.LENGTH_LONG).show();
			finish();
			break;

		case FAIL:
			//정보 얻어오기 실패
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, (String)_message.obj, Toast.LENGTH_SHORT).show();
			break;
		case NETWORK_ERR:
			//네트워크 오류 또는 제이슨 에러 
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Main_JoinMember", "미가입 회원");
			
			break;
		case EMAIL_CHECK:
			//이메일 중복 체크
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			check_email = true;
			Toast.makeText(this, (String)_message.obj,  Toast.LENGTH_SHORT).show();
			break;
			
		case SEARCH_ADDR:
			//주소 검색
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			AlertDialog.Builder alert = new AlertDialog.Builder(this);

			alert.setTitle("주소선택");
			ListView listView = new ListView(this);

			ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, addname);
			listView.setAdapter(dataAdapter);
			alert.setView(listView);

			final DialogInterface mPopupDlg = alert.show();
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					addposition = addcode.get(position);
					startNetwork(SEARCH_SCHOOL);
					mPopupDlg.dismiss();
				}
			});
			
			break;
		
		case SEARCH_SCHOOL:
			//유치원 검색
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			schoolname = new ArrayList<String>();
			for (int i = 0; i < schoollist.size(); i++) {
				schoolname.add(schoollist.get(i).Sch_Name);
			}
			AlertDialog.Builder schoolalert = new AlertDialog.Builder(this);

			schoolalert.setTitle("원선택");
			ListView schoollistView = new ListView(this);

			ArrayAdapter<String> schooldataAdapter = new ArrayAdapter<String>(
					this, android.R.layout.simple_list_item_1, schoolname);
			schoollistView.setAdapter(schooldataAdapter);
			schoolalert.setView(schoollistView);

			final DialogInterface schoolmPopupDlg = schoolalert.show();
			schoollistView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					tv.setText(schoollist.get(position).Sch_Name);
					sch = schoollist.get(position).PK_Sch_Code + "";
					schoolmPopupDlg.dismiss();
				}
			});
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.MAIN_JOIN_EMAIL_CHECK:
			if (!isEmailValid(et[0].getText().toString())){
				Toast.makeText(this,"이메일 형식에 맞춰 작성 해주세요.",Toast.LENGTH_SHORT).show();
			}else{
			startNetwork(EMAIL_CHECK);
			}
			break;
		
		case R.id.MAIN_JOIN_SCHOOL_SEARCH:
			AlertDialog.Builder alert = new AlertDialog.Builder(this);

			alert.setTitle("동선택");
			alert.setMessage("읍,면,동,리의 단위로 입력해주세요");

			// Set an EditText view to get user input
			final EditText input = new EditText(this);
			alert.setView(input);

			alert.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							addr = input.getText().toString();
							startNetwork(SEARCH_ADDR);
						}
					});

			alert.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// Canceled.
						}
					});

			alert.show();
			break;
			
		case R.id.MAIN_JOIN_BTN:
			alertDialog();
			break;
		}
	}
	
	protected void showAddress() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_URL, "code="+CODE_MAIN_JOIN_SELADDR+"&name=" + addr ));
			if (jsonObject.getBoolean("success")) {
				addcode = new ArrayList<String>();
				addname = new ArrayList<String>();
				JSONArray ja = new JSONArray(jsonObject.getString("payload"));
				JSONObject jo;
				for (int i = 0; i < ja.length(); i++) {
					jo = ja.getJSONObject(i);
					addcode.add(jo.getString("PK_Add_Code"));
					addname.add(jo.getString("Add_Si") + " "
							+ jo.getString("Add_Gu") + " "
							+ jo.getString("Add_Dong") + " "
							+ jo.getString("Add_Ri"));

				}
				onNetworkCallback(SEARCH_ADDR, "");
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR, e.toString()+" where showAddress()");
		}
		;
	}

	protected void selectSchool() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code="+CODE_MAIN_JOIN_SELSCH+ "&position=" + addposition));
			if (jsonObject.getBoolean("success")) {
				schoollist = JsonParser.SelectSchool(jsonObject.getString("payload"));
				onNetworkCallback(SEARCH_SCHOOL,
						jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where selectSchool()");
		}
		;
	}

	
	void mainThread(int cho){
		email = et[0].getText().toString();
		name = et[3].getText().toString();
		String code="";
		if (cho == EMAIL_CHECK){
			code = "code="+CODE_MAIN_JOIN_CHECK_EMAIL+"&PK_Mem_Email="+email;
		}
		if (cho == SUCCESS){
			code = "code="+CODE_MAIN_JOIN+"&PK_Mem_Email="+email+"&Mem_Pass="+pass+"&Mem_Sch="+sch+"&Mem_Name="+name+"&Mem_Uuid="+regId+"&Mem_Rank="+rank;
		}
		
		try {

			JSONObject	jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					code));

			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(cho, jsonObject.getString("payload"));				
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR, e.toString()+" where mainThread()");
		}
	}
	
	// 메일 양식 체크
		boolean isEmailValid(CharSequence email) {
			return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
		}
		
	//모든 양식 체크 
		void check_form(){
			check = 0;
			if (et[0].getText().toString().equals("")) {
				check_email = false;
				Toast.makeText(this, "아이디를 입력해 주세요", Toast.LENGTH_SHORT).show();
				check = 1;
			} else if (et[1].getText().length() < 8
					|| et[1].getText().length() > 15) {
				Toast.makeText(this,"패스워드를 8자~15자로 입력하세요.", Toast.LENGTH_SHORT).show();
				check = 1;
			} else if (et[2].getText().toString().length() < 0) {
				Toast.makeText(this,"패스워드확인을 입력해주세요.", Toast.LENGTH_SHORT).show();
				check = 1;
			} else if (!et[2].getText().toString()
					.equals(et[1].getText().toString())) {
				Toast.makeText(this,"패스워드체크가 일치하지 않습니다.", Toast.LENGTH_SHORT).show();
				check = 1;
			} else if (et[3].getText().length() < 2) {
				Toast.makeText(this,"닉네임을 입력하세요.", Toast.LENGTH_SHORT).show();
				check = 1;
			} else if (sch.equals("")) {
				tv.setHint("유치원을 선택하세요.");
				check = 1;
			}
			
		if(check==0 && check_email==true && check_name==true){
			radioButton = (RadioButton) findViewById(radioGroup
					.getCheckedRadioButtonId());
			String choice_rb = radioButton.getText().toString();
			if (choice_rb.equals("학부모")) {
				rank = "3";
			} else if (choice_rb.equals("선생님")) {
				rank = "2";
			} else if (choice_rb.equals("원장님")) {
				rank = "0";
			} // 원장대기=0
			
			pass = et[1].getText().toString();
			startNetwork(SUCCESS);
		}
		else if (check_email==false){
			Toast.makeText(this, "이메일 중복체크를 해주세요.", Toast.LENGTH_SHORT).show();
		}else if (check_name==false){
			Toast.makeText(this, "닉네임은 특수문자 사용이 불가 합니다.", Toast.LENGTH_SHORT).show();
		}
	}

		// 네.아니오.선택다이얼로그
				void alertDialog() {
					
					AlertDialog.Builder builder = new AlertDialog.Builder(
							this);
					AlertDialog alert;
					builder.setMessage("입력한 내용으로 회원가입 하시겠습니까?")
							.setCancelable(false)
							.setPositiveButton("네", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									check_form();
								}
							})
							.setNegativeButton("아니오",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									});
					alert = builder.create();
					alert.show();
				}


}
